<?php
/**
 * Created by PhpStorm.
 * userValidate: gh
 * Date: 2018/5/31
 * Time: 13:50
 */
namespace app\Tools;
 
    class VerifyCodeImage {
        private $width;
        private $height;
        private $str;
        private $im;
        private $strColor;
 
        function __construct($width, $height,$image_code) {
            $this->width  = $width;
            $this->height = $height;
            $this->str    = $image_code;
            $this->createImage();
        }
 
        /**
         * 生成图片二维码
         */
        function createImage() {
            $this->im = imagecreate($this->width, $this->height);//创建画布
            $randColor = imagecolorallocate($this->im, rand(200,220),rand(200,220),rand(200,220));//为画布添加颜色
            for ($i = 0; $i < strlen($this->str); $i++) {//循环输出四个数字
                $this->strColor = imagecolorallocate($this->im, rand(50, 160), rand(50, 160), rand(50, 160));
                imagettftext($image, 40, 40, 200, 200, $randColor, 'fonts/courbi.ttf', $this->str);
                imagestring($this->im, rand(3, 5), $this->width / 4 * $i + rand(5, 10), rand(2, 5), $this->str[$i], $this->strColor);
            }

//            for ($i = 0; $i < 100; $i++) {//循环输出200个像素点
//                $this->strColor = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255));
//                imagesetpixel($this->im, rand(0, $this->width), rand(0, $this->height), $this->strColor);
//            }
        }
 
 
        /**
         * 生成图片二维码并保存
         * @return string
         */
        function show() {
            ob_start ();
            header('content-type:image/png');//定义输出为图像类型
            imagepng($this->im);//生成图像
            imagedestroy($this->im);//销毁图像释放内存
            $imageData = ob_get_contents ();
            ob_end_clean ();
            $imageDataBase64 = "data:image/png;base64,". base64_encode ($imageData);
            return $imageDataBase64;
        }
        
        
    }